#include "mybattery.h"
#include <QPainter>

MyBattery::MyBattery(QWidget *parent) : QWidget(parent)
{

}

int MyBattery::powerLevel() const
{
    return mPowerLevel;
}

void MyBattery::setPowerLevel(int powerLevel)
{
    mPowerLevel = powerLevel;
    repaint();
}

int MyBattery::warning() const
{
    return mWarning;
}

void MyBattery::setWarning(int warning)
{
    mWarning = warning;
}

void MyBattery::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QRect rect(0, 0, width(), height());
    painter.setViewport(rect);
    painter.setWindow(0,0, 120, 50);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);

    //绘制电池边框
    QPen pen;
    pen.setWidth(2);
    pen.setColor(mColorBorder);
    pen.setStyle(Qt::SolidLine);
    pen.setCapStyle(Qt::FlatCap);
    pen.setJoinStyle(Qt::BevelJoin);
    painter.setPen(pen);

    QBrush brush;
    brush.setColor(mColorBackGroud);
    brush.setStyle(Qt::SolidPattern);
    painter.setBrush(brush);

    rect.setRect(1,1, 109, 48);
    painter.drawRect(rect);
    brush.setColor(mColorBackGroud);
    painter.setBrush(brush);

    rect.setRect(110, 15, 10, 20);
    painter.drawRect(rect);

    //画电量
    if(mPowerLevel > mWarning)
    {
        brush.setColor(mColorPowerHealthy);
        pen.setColor(mColorPowerHealthy);
    } else{
        brush.setColor(mColorPowerWarning);
        pen.setColor(mColorPowerWarning);
    }
    painter.setBrush(brush);
    painter.setPen(pen);
    if(mPowerLevel > 0)
    {
        rect.setRect(5,5,mPowerLevel, 40);
        painter.drawRect(rect);
    }

    //绘制百分比文字
    QFontMetrics textSize(this->font());
    QString powStr = QString::asprintf("%d%%", mPowerLevel);
    QRect textRect = textSize.boundingRect(powStr);
    pen.setColor(mColorBorder);
    painter.setPen(pen);
    painter.drawText(55 - textRect.width() /2 , 23 + textRect.height() /2, powStr);
}
